import os
import json
import streamlit as st
from langchain_core.messages import HumanMessage
import pandas as pd
from models.user import manage_login, User, register_user
from services.AccessChartGPT import *
from utils.genQRCode import show_qr_in_chat
from utils.OrderUtil import update_order_hist
from utils.json_utils import split_response
from services.payment.payment_service import handle_payment
from services.recommendation_service import RecommendationService

def LoginPage():
    """处理用户登录页面"""
    if not st.session_state.user.isValid():
        print("User not logged in.")
        if manage_login():  # 如果登录成功
            initAgent(st.session_state)
            st.session_state.current_page = "main"
            st.rerun()
            
        # 添加注册按钮
        if st.button("Register New Account"):
            st.session_state.current_page = "register"
            st.rerun()    
        return False
    return True

def RegisterPage():
    """处理用户注册页面"""
    st.title("User Registration")
    if register_user():
        st.session_state.current_page = "login"  # 注册完成后跳转到登录页
        st.rerun()
    return False


def MainPage():
    # 设置侧边栏
    with st.sidebar:
        st.title("SportsHub")
        st.markdown("---")
        # 显示用户信息
        st.markdown(f"**Current user:** {st.session_state.user.getName()}")
        st.markdown(f"**Role:** {st.session_state.user.getRole()}")
        st.markdown(f"**Email:** {st.session_state.user.getEmail()}")
        st.markdown("---")
        if st.button("Logout"):
            st.session_state.user.logout()
            st.rerun()

    # 显示主界面内容
    if st.session_state.user.isValid():
        st.title("SportsHub - Sports Event Ticketing System")
        st.markdown(f"Welcome to SportsHub, {st.session_state.user.getName()}!")

        # 使用st.form包裹推荐按钮，避免阻塞
        with st.form("recommendation_form"):
            if st.form_submit_button("🌟 Get Local Sports Event Recommendations",
                                  help="Click to find sports events near your location"):
                with st.spinner("Fetching recommendations..."):
                    rec_service = RecommendationService()
                    recommendations = rec_service.get_recommendations("sports events near me")
                    
                    if recommendations.get("success"):
                        st.session_state.recommendation_data = recommendations['data']
                        st.session_state.recommendation_map = recommendations['map_file']
                    else:
                        st.error(f"Failed to get recommendations: {recommendations.get('error')}")

        # 显示推荐结果（如果有）
        if hasattr(st.session_state, 'recommendation_data'):
            st.subheader("Recommended Events")
            st.json(st.session_state.recommendation_data)
            
            if hasattr(st.session_state, 'recommendation_map'):
                with open(st.session_state.recommendation_map, 'r') as f:
                    st.components.v1.html(f.read(), height=500)

        # 显示系统说明
        with st.expander("System Information"):
            st.markdown("""
            **SportsHub Sports Event Ticketing System** is an intelligent ticketing assistant that can help you:
            
            1. Query information about various sports events
            2. Learn about ticket prices and seat class
            3. Check remaining tickets
            4. Purchase event tickets
            
            Please enter your needs in the chat box below, for example:
            - "I want to know what football matches are available"
            - "How much are NBA game tickets"
            - "I want to buy tickets for a tennis match"
            """)


        # 初始化聊天历史
        if "messages" not in st.session_state:
            st.session_state.messages = []
            # 添加欢迎消息
            welcome_msg = "Hello {}! I'm the SportsHub Smart Ticketing Assistant. Which sport are you interested in—Football, Basketball, Tennis, or Golf?".format(
                st.session_state.user.getName() if st.session_state.user.isValid() else "Guest")
            st.session_state.messages.append({"role": "assistant", "content": welcome_msg})

        # 更新历史消息
        for msg in st.session_state.messages:
            with st.chat_message(msg["role"]):
                st.markdown(msg["content"])
                if msg.get("show_image") and msg.get("image"):
                    st.image(msg["image"], caption="", width=200)

        # 用户输入区域
        if user_input := st.chat_input("Enter your question or request..."):
            # 添加用户消息到历史
            st.session_state.messages.append({"role": "user", "content": user_input})

            with st.chat_message("user"):
                st.markdown(user_input)

            with st.chat_message("assistant"):
                with st.spinner("Thinking..."):
                    # 调用 AI 模型获取回复
                    print("用户输入", user_input)
                    msg = SendMessage(st.session_state.agent, st.session_state.config, [HumanMessage(user_input)])
                    print("原始 LLM 响应", msg)
                    text_part, json_part = split_response(msg)
                    print("文本部分", text_part)
                    print("JSON 部分", json_part)

                    if text_part is not None:
                        st.markdown(text_part)
                        # 添加 AI 回复到历史
                        st.session_state.messages.append({"role": "assistant", "content": text_part})

                    if json_part is not None:
                        # 检查 json_part 类型，如果是字符串则解析，否则直接使用
                        if isinstance(json_part, str):
                            st.session_state.order_data = json.loads(json_part)
                        else:
                            st.session_state.order_data = json_part

                        # print("订单数据状态", st.session_state.order_data["completed"])

    # 检查是否需要显示二维码
    if hasattr(st.session_state, 'order_data') and st.session_state.order_data is not None:
        if st.session_state.order_data.get("completed", False):
            show_qr_in_chat(st, st.session_state.order_data)

            print("开始处理支付流程")

            if handle_payment(st.session_state.order_data, st.session_state.user.getEmail()):
                st.success("支付成功！")
                update_order_hist(st.session_state.order_data)

            del st.session_state.order_data

            st.rerun()


if __name__ == "__main__":
    current_dir = os.getcwd()
    print(f"当前工作目录是: {current_dir}")
    # 设置页面配置
    st.set_page_config(
        page_title="SportsHub - Sports Event Ticketing System",
        page_icon="🏆",
        layout="wide",
        initial_sidebar_state="expanded"
    )
    # 初始化用户对象
    if "user" not in st.session_state:
        st.session_state.user = User()  # 创建用户对象，并添加到 session_state 中
        st.session_state.agent = None  # 初始化 agent
        st.session_state.config = None  # 初始化 config
        st.session_state.order_data = None  # 初始化订单数据
        st.session_state.current_page = "login"  # 默认显示登录页
    # 页面路由
    if st.session_state.current_page == "login":
        LoginPage()
    elif st.session_state.current_page == "register":
        RegisterPage()
    elif st.session_state.current_page == "main":
        MainPage()
    else:
        st.error("Unknown page")